﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using System.Web.Services.Protocols;

namespace Aliyeye.Car.Net.WebService
{
    public class SoapExceptionHelper
    {
        /// <summary>
        /// 异常类型
        /// </summary>
        public enum FaultCode
        {
            Client = 0,
            Server = 1
        }

        /// <summary>
        /// 封装异常为SoapException
        /// </summary>
        /// <param name="uri">引发异常的方法uri</param>
        /// <param name="errorMessage">错误信息</param>
        /// <param name="errorSource">错误来源</param>
        /// <param name="code">异常类型</param>
        /// <returns>封装后的SoapException</returns>
        public static SoapException RaiseException(string uri, string errorMessage, string errorSource, FaultCode code)
        {
            //初始化限定名
            XmlQualifiedName faultCodeLocation = null;

            //异常类型代码转换
            switch (code)
            {
                case FaultCode.Client:
                    faultCodeLocation = SoapException.ClientFaultCode;
                    break;
                case FaultCode.Server:
                    faultCodeLocation = SoapException.ServerFaultCode;
                    break;
            }

            //构建异常信息结构体
            string strXmlOut = @"<detail>"
                             + "<ErrorMessage>" + errorMessage + "</ErrorMessage>"
                //+ "<ErrorSource>" + errorSource + "</ErrorSource>"
                             + "</detail>";

            //装载为Xml文档
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(strXmlOut);

            //实例化SoapException
            SoapException soapEx = new SoapException(errorMessage, faultCodeLocation, uri, xmlDoc.DocumentElement);
            //返回SoapException
            return soapEx;
        }

        /// <summary>
        /// Get Error Message from SOAPException
        /// </summary>
        /// <param name="soapException"></param>
        /// <returns></returns>
        public static string GetSoapExMsg(SoapException soapException)
        {
            return soapException.Detail.ChildNodes[0].InnerText;
        }
        /// <summary>
        /// Get Error Source from SOAPException
        /// </summary>
        /// <param name="soapException"></param>
        /// <returns></returns>
        public static string GetSoapExSource(SoapException soapException)
        {
            return soapException.Detail.ChildNodes[1].InnerText;
        }

        /// <summary>
        /// 判断异常类型是否为服务器无响应
        /// </summary>
        /// <param name="soapException"></param>
        /// <returns></returns>
        public static bool IsServiceDisconnectedException(Exception soapException)
        {
            return String.Equals(soapException.TargetSite.Module.Name, "System.Web.Services.dll");
        }
    }
}
